package com.lkj.youmeng.mvp.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;

import androidx.appcompat.widget.AppCompatImageView;

import com.lkj.youmeng.R;

import java.lang.ref.WeakReference;

public class MergeImageView extends AppCompatImageView {
    private Paint mPaint;
    private PorterDuffXfermode mXfermode;
    private Bitmap mMaskBitmap;
    private WeakReference<Bitmap> mWeakBitmap;
    private int type;
    private static final int TYPE_CIRCLE = 1;
    private static final int TYPE_ROUND = 0;
    private static final int BODER_RADIUS_DEFAULT = 10;
    private int mBorderRadius;

    public MergeImageView(Context context) {
        super(context);
    }

    public MergeImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context,attrs);
    }

    public MergeImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context,attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (type == TYPE_CIRCLE) {
            int width = Math.min(getMeasuredWidth(), getMeasuredHeight());
            setMeasuredDimension(width, width);    //设置当前View的大小
        }else {
            Drawable drawable = getDrawable();
            if (drawable != null){
                int width = drawable.getIntrinsicWidth();
                int height = drawable.getIntrinsicHeight();
                float scale = Math.min(getMeasuredWidth() * 1.0f / width, getMeasuredHeight()
                        * 1.0f / height);
                int rw = (int) (scale * width);
                int rh = (int) (scale * height);
                int dw = Math.min(rw,getMeasuredWidth());
                int dh = Math.min(rh,getMeasuredHeight());
                setMeasuredDimension(dw, dh);
            }else {
                setMeasuredDimension(getMeasuredWidth(), getMeasuredHeight());
            }

        }

    }

    private void init(Context context, AttributeSet attrs) {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.FILL);
        mXfermode = new PorterDuffXfermode(PorterDuff.Mode.DST_IN);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MergeImageView);
        mBorderRadius = typedArray.getDimensionPixelSize(R.styleable.MergeImageView_Radius,BODER_RADIUS_DEFAULT);
        type = typedArray.getInt(R.styleable.MergeImageView_type,TYPE_ROUND);
        typedArray.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //在缓存中取出bitmap
        Bitmap bitmap = mWeakBitmap == null?null:mWeakBitmap.get();
        if (bitmap == null|| bitmap.isRecycled()){
            //获取图片宽高
            Drawable drawable = getDrawable();

            if (drawable != null) {
                int width = drawable.getIntrinsicWidth();
                int height = drawable.getIntrinsicHeight();
                bitmap = Bitmap.createBitmap(getWidth(),getHeight(), Bitmap.Config.ARGB_8888);
                Canvas drawCanvas = new Canvas(bitmap);
                float scale = 1.0f;
                if (type == TYPE_ROUND){
                    scale = Math.min(getWidth() * 1.0f / width, getHeight()
                            * 1.0f / height);
                }else {
                    scale = getWidth() * 1.0F / Math.min(width, height);
                }
                //根据缩放比例，设置bounds，相当于缩放图片了
                drawable.setBounds(0, 0, (int) (scale * width),
                        (int) (scale * height));
                drawable.draw(drawCanvas);
                if (mMaskBitmap == null || mMaskBitmap.isRecycled()) {
                    mMaskBitmap = getBitmap();
                }
                mPaint.reset();
                mPaint.setFilterBitmap(false);
                mPaint.setXfermode(mXfermode);
                drawCanvas.drawBitmap(mMaskBitmap,0,0,mPaint);
                mWeakBitmap = new WeakReference<Bitmap>(bitmap);
                canvas.drawBitmap(bitmap,0,0,null);
                mPaint.setXfermode(null);
            }
        }

        if (bitmap != null) {
            mPaint.setXfermode(null);
            canvas.drawBitmap(bitmap, 0.0f, 0.0f, mPaint);
            return;
        }
    }

    //缓存Bitmap，避免每次OnDraw都重新分配内存与绘图
    @Override
    public void invalidate() {
        mWeakBitmap = null;
        if (mWeakBitmap != null) {
            mMaskBitmap.recycle();
            mMaskBitmap = null;
        }
        super.invalidate();
    }

    //定义一个绘制形状的方法

    private Bitmap getBitmap() {
        Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);   //抗锯齿
        paint.setColor(Color.BLACK);
        if (type == TYPE_ROUND) {
            Path path = new Path();
            path.addRoundRect(new RectF(0,0,getWidth(),getHeight()),new float[]{10,10,10,10,0,0,0,0}, Path.Direction.CCW);
//            canvas.drawRoundRect(new RectF(0, 0, getWidth(), getHeight()),
//                    mBorderRadius, mBorderRadius, paint);
            canvas.drawPath(path,paint);
        } else {
            canvas.drawCircle(getWidth() / 2, getWidth() / 2, getWidth() / 2, paint);
        }
        return bitmap;
    }

    public void setType(int type){
        this.type = type;
    }
}
